import { defineStore } from "pinia"
import {
  getAddressList,
  getAddressDetail,
  updateAddress,
  addAddress,
  removeAddress,
} from "@/api/address"
import router from "@/router/router"
import { showToast } from "vant"
const useAddressStore = defineStore({
  id: "address",
  state: () => ({
    addressList: [],
    chosenAddressId: "",
    addressDetail: {},
  }),
  actions: {
    // 获取地址列表
    async asyncGetAddressList() {
      const res = await getAddressList()
      this.addressList = res.data.map(item => {
        return {
          id: item.addressId,
          name: item.userName,
          tel: item.userPhone,
          address: item.provinceName + item.cityName + item.regionName + item.detailAddress,
          isDefault: item.defaultFlag ? 1 : 0,
        }
      })
      this.chosenAddressId = this.addressList.filter(item => item.isDefault == true)[0].id
    },
    // 获取地址详情
    async asyncGetAddressDetail(id) {
      const res = await getAddressDetail(id)
      this.addressDetail = {
        id: res.data.addressId,
        name: res.data.userName,
        tel: res.data.userPhone,
        province: res.data.provinceName,
        city: res.data.cityName,
        county: res.data.regionName,
        addressDetail: res.data.detailAddress,
        isDefault: res.data.defaultFlag ? true : false,
      }
    },
    //新增地址
    async asyncAddAddress(obj) {
      const res = await addAddress(obj)
      if (res.resultCode === 200) {
        showToast("添加成功")
        router.push("/addressList")
      }
    },
    // 编辑地址
    async asyncUpdateAddress(obj) {
      const res = await updateAddress(obj)
      if (res.resultCode === 200) {
        showToast("修改成功")
        router.push("/addressList")
      }
    },
    // 删除地址
    async asyncRemoveAddress(id) {
      const res = await removeAddress(id)
      if (res.resultCode === 200) {
        showToast("删除成功")
        router.push("/addressList")
      }
    },
  },
})
export default useAddressStore
